/*
 * 分类弹窗
 * 功能：显示子分类
 */

(function(factory){
    if(typeof define === 'function' && define.amd){
        define(['jquery','catedb','bDialog/dialog'],factory);
    }else{
        factory(window.jQuery);
    }
}(function($){    

    $.fn.CateB = function(o) {
        var that = $.extend({},$.fn.CateB.defaults, o);
        return this.each(function() {
            var t = $(this);
            var ThatData=new Array();
            
            t.click(function(){
                _data.clear();
                var arthtml='',arthtmllist='';
                
                var catett=new Array();
                var tnum=1;
                arthtml=$('<div class="dl-data"></div>');
                var arthtml2='';
                if(that.type !== 'radio'){
                    arthtml2+='<div class="trade-hd"><strong class="brown">最多可以选择 '+that.max+' 项</strong>';
                } else {
                    arthtml2 += '<div>';
                }                
                arthtml2 += '<div class="cols-all">';
                if(that.type !== 'radio') arthtml2 += '<input type="checkbox" data-code="0,不限" name="item-all" class="input-checkbox"><label>不限</label>';
                arthtml2 += '</div></div>';
                arthtml2 += '<div class="dlresult"><span class="fat">您选择的是：</span><div class="sel"></div></div>'
                         + '<div class="catett"><div></div></div><div class="loading">正在加载...</div><div class="col-list"></div>'
                         + '<div class="fc"></div>';
                arthtml.append(arthtml2);
                
                var dl=dialog({
                    title: that.title,
                    padding:'0px',
                    content: arthtml,
                    ok: function () {
                        //从 ID sel_show 中获取 选择内容
                        var namestr = '';
                        var show_namestr = '';
                        var pathstr = '';
                        var namearr=[], patharr=[],idarr=[],typearr=[];
                        for (var i = 0; i < _data.item.length; i++){
                            patharr.push(_data.item[i][0]);
                            namearr.push(_data.item[i][1]);
                            idarr.push(_data.item[i][2]);
                            typearr.push(_data.item[i][4]);//类型
                        }
                        namestr = show_namestr = namearr.join(",");
                        pathstr = patharr.join(",");

                        var namestr_len = namestr.length;
                        if(namestr_len>that.cutstr) show_namestr = namestr.substring(0,that.cutstr)+'...';

                        if(that.valtype=='id'){
                            $(that.input).val(idarr.join(","));
                        }else{
                            $(that.input).val(pathstr);
                        }


                        if(show_namestr == ''){
                            show_namestr = that.default_val;
                        }
                        if(that.showdiv){
                            $(that.showdiv).html(show_namestr);
                        }else{
                            if($(t).data('show')!=='none'){
                                if($(t).is('input')){
                                    $(t).val(show_namestr);
                                }else{
                                    $(t).html(show_namestr);
                                }
                            }
                        }
                        if(ThatData.length>1){
                            $(that.input).attr('dbtype',typearr.join(","));
                        }
                        if($.isFunction(that.fn)){ that.fn(_data.item);}
                        return true;
                    },cancel:function(){}
                });

                var wrap=$(arthtml),
                list=wrap.find(".col-list"),
                chkAll=wrap.find(".cols-all input");
                
                if(that.url){
                    var url = that.url;
                    url=url.split('|');
                    tnum=url.length;
                    for(var i=0;i<tnum;i++){
                        if(url[i].indexOf('@')>0){
                            var urlarr=url[i].split('@');
                            arthtml.find('.catett').show().find('div').append('<span>'+urlarr[0]+'</span>');                            
                            ajaxdb(i,urlarr[1]);
                        }else{
                            ajaxdb(0,url[i]);
                        }
                    }                    
                }else{
                    $(arthtml).find('.col-list').append('<ul style="display:none;"></ul>');
                    ThatData[0]=LocalData[that.name][0];
                    gethtml(0);
                }
                
                function ajaxdb(j,url){
                    $(arthtml).find('.col-list').append('<ul style="display:none;"></ul>');                    
                    $.ajax({url:url,success:function(result){
                        ThatData[j]= result;
                        gethtml(j);
                    },error: function () {
                        ThatData[j]=new Array();
                        gethtml(j);
                    },dataType:'jsonp',async:false});
                }
                function getlength(data){
                    var s=0;
                    $.each(data,function(i,n){
                        s++;
                    });
                    return s;
                }
                function gethtml(x){
                    arthtmllist='';
                    var tdnum=getlength(ThatData[x]);
                    if(tdnum){
                        var k=0;
                        arthtmllist+='<li>';
                        $.each(ThatData[x],function(i,n){
                            var sdata =n;
                            //排除-通用职能
                            if(n.id!=504){
                                k++;
                                //var liw=$(arthtml).find('.col-list').width()/that.col;
                                var liw=480/that.col;
                                arthtmllist+='<div class="item" style="width:'+liw+'px"><i class="dot"></i><span code="'+sdata.id+'" data-code="'+sdata.path+','+sdata.name+','+sdata.id+','+sdata.position+','+x+'" >'+sdata.name+'</span></div>';
                                
                                if(k%that.col == 0 && k<tdnum){
                                    arthtmllist+='</li><li>';
                                }
                            }
                        });  
                        arthtmllist+='</li>';
                    }else{
                        arthtmllist+='<li class="noinfo">暂无数据！</li>';
                    }
                    arthtmllist+='';
                    
                    $(arthtml).find('.col-list ul').eq(x).append(arthtmllist);                    
                    if(tnum-1==x){
                        //加载完成=====================
                        $(arthtml).find('.loading').remove();
                        if(tnum>1){ 
                            arthtml.find('.catett span').click(function(){
                                $(this).addClass('active').siblings().removeClass('active');
                                arthtml.find('.col-list ul').eq($(this).index()).show().siblings().hide();
                            }).eq(0).click();
                        }
                        arthtml.find('.col-list ul:first').fadeIn();
                        
                        var list=wrap.find(".col-list"),
                        chkAll=wrap.find(".cols-all input");
        
                        initdb();                        
                    }
                }

                if(that.type!=="checkbox"){
                    wrap.find(".cols-all").hide();
                }
                function createsub(z,id,x,pitem){

                    var n=ThatData[x][id];
                    if(n.child){
                        arthtmllist = '<div class="sub" style="display:none">';
                        //if(that.type !== 'radio')
                        arthtmllist += '<span class="li"><input type="' + that.type + '" name="item-children" code="'+pitem[0]+'" data-code="'+pitem+'" class="input-checkbox">全选</span>';
                        $.each(n.child,function(l,m){
                            arthtmllist += '<span class="li"><input class="cat input-' +  that.type + '" type="' + that.type + '" name="item-children" value="' +m.path+','+m.name+','+m.id+','+m.position+','+x+ '"  data-code="'+m.path+','+m.name+','+m.id+','+m.position+','+x+'" code="' + m.path + '" /><label>'+ m.name + '</label></span>';
                        });
                        arthtmllist += '<div class="fc"></div></div>';
                        $(z).append(arthtmllist);
                        var w=$(z).find('.sub').width();
                        $(z).find('.sub .li').width(w/that.col-10);
                        $(z).find('.sub').show();

                    }
                }
                //一级全选
                list.on('click','li .item span',function(){
                    $(this).parents('ul').find('.item').removeClass('s');
                    $(this).parents('ul').find('.sub').remove();
                    $(this).parent().addClass('s');
                    
                    var id=$(this).attr('code');
                    var item = $(this).attr("data-code").split(",");
                    if(ThatData[item[4]][id].child){
                        createsub($(this).parents('li'),id,item[4],item);
                    }else{
                        var parent = $(this).parent();
                        if(that.type=="radio"){
                            _data.clear();
                        }
                        _data.push(item);
                        $(this).addClass('checked');
                        chkmax();
                    }
                });
                
                $(list).off('change').on('change','.sub input', function(){
                    var sinput=$(this);
                    var item = sinput.attr("data-code").split(",");
                    if(sinput.is(":radio")){
                        _data.clear();
                        list.find('li > span').removeClass('checked');
                        list.find('li > span').removeClass('disabled');
                    }
                    _data.push(item);
                    
                    chkmax();
                });
                
                function chkmax(){
                    if (that.max !== 0) {
                        if (that.type !== "radio" && _data.item.length >= that.max) {
                            list.find("input").not(":checked").prop("disabled",true);
                        } else {
                            list.find("input").filter(":disabled").not(':checked').prop("disabled",false);
                        }
                    }
                }
                
                _data.result = wrap.find(".sel");

                _data.result.delegate("a", "click", function() {
                    var code = $(this).attr("data-code").split(","),
                    _code = "";
                    _data.remove(code);
                    $(this).remove();
                    
                    $.each(ThatData,function(a,b){
                        $.each(ThatData[a],function(i,n){
                            if (code[0] == n.path){
                                _code = n.path;
                            }
                            if(n.child){
                                $.each(n.child,function(l,m){
                                    if (code[0] == m.path){
                                        _code = m.path;
                                    }
                                });
                            }
                        });
                    });

                    if (_code) {
                        var _subitem = list.find("li input[code='" + code[0] + "']");
                        if (_subitem.length > 0) {
                            var parentTagName = _subitem.parent().prop('tagName').toLowerCase();
                            if(parentTagName=='span'){
                                _subitem.parent().siblings('.sub').find("input:disabled").prop("disabled", false).prop("checked", false);
                            } else {
                                list.find("li input:disabled").not(':checked').prop("disabled", false).prop("checked", false);
                            }
                            _subitem.prop("checked", false).siblings('i').removeClass('checked');
                        } else {
                            if (list.find("li.li-all input:checked").length === 0) {
                                list.find("li input:disabled").prop("disabled", false);
                            }
                        }
                    } else if (code[0] === "0") {
                        chkAll.prop("checked", false);
                        list.find("li input").prop("checked", false).prop("disabled", false);
                    }
                });
                wrap.find(".cols-all").delegate('input','click',function(){
                //chkAll.live("click", function() {
                    var item = $(this).attr("data-code").split(","),
                    checked = this.checked;
                    if (checked) {
                        _data.clear();
                        _data.push(item);
                        list.find("input").prop("checked", true).prop("disabled", true);
                    } else {
                        _data.remove(item);
                        list.find("input").prop("checked", false).prop("disabled", false);
                    }
                });
                _data.init();
            });
            
            if(that.url){
                    
            }else{
                ThatData[0]=LocalData[that.name][0];
                initdb(1);
            }
            /*初始化数据===============================*/
            function finditem(ids,s){
                $.each(ThatData,function(a,b){
                    $.each(ThatData[a],function(i,n){
                        if (ids == n.path){
                            var _item=[n.path,n.name,n.id,n.position,a];
                            if(s){
                                var namestr=_item[1];
                                var namestr_len = namestr.length;
                                if(namestr_len>that.cutstr) namestr=namestr.substring(0,that.cutstr)+'...';
                                
                                if(that.showdiv){
                                    $(that.showdiv).html(namestr);
                                }else{
                                    if($(t).data('show')!=='none'){
                                        if($(t).is('input')){
                                            $(t).val(namestr);
                                        }else{
                                            $(t).html(namestr);
                                        }
                                    }
                                }
                            }else{
                                _data.push(_item);
                            }
                            return;
                        }
                        if(n.child){
                            $.each(n.child,function(l,m){
                                if (ids == m.path){
                                    var _item=[m.path,m.name,m.id,m.position,a];
                                    if(s){
                                        var namestr=_item[1];
                                        var namestr_len = namestr.length;
                                        if(namestr_len>that.cutstr) namestr=namestr.substring(0,that.cutstr)+'...';
                                        if(that.showdiv){
                                            $(that.showdiv).html(namestr);
                                        }else{
                                            if($(t).data('show')!=='none'){
                                                if($(t).is('input')){
                                                    $(t).val(namestr);
                                                }else{
                                                    $(t).html(namestr);
                                                }
                                            }
                                        }
                                    }else{
                                        _data.push(_item);
                                    }
                                    return;
                                }
                            });
                        }
                    });
                });
            }
            function initdb(s){
                var ids=$(that.input).val(),idsarr=[];
                if(ids != ''){
                    idsarr = ids.split(",");
                    for (var i = 0; i < idsarr.length; i++){                            
                        finditem(idsarr[i],s);
                    }
                }                    
            }
        });
    };
    $.fn.CateB.defaults = {
        title: "请选择",
        max:5,
        type: "checkbox",
        allVal: ["", "全部", "All"],
        cutstr:10,
        col:2, //一行显示条数
        default_val:"请选择",
        showdiv:''
    };
}));